<template>
	<view class="content">
		<view class="uni-list">
			<radio-group @change="radioChange">
				<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items" :key="item.value">
					<view>
						<radio :value="item.value" :checked="index === current" />
					</view>
					<view>{{item.name}}</view>
				</label>
			</radio-group>
		</view>
		<view v-if="current === 1">
			<view class="input">
				<input type="text" placeholder="请输入写入内容" v-model="keyWord" @input="handChange" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		initNFC,
		closeNFC,
		setNfcType,
		setNfcText
	} from '@/uni_modules/wufeng-nfc/js_sdk/nfc.js';
	let timer = null
	export default {
		data() {
			return {
				keyWord: '',
				items: [{
						value: 'cardNo',
						name: '读取卡号',
						checked: 'true'
					},
					{
						value: 'write',
						name: '写入内容'
					},
					{
						value: 'read',
						name: '读取内容'
					},
				],
				current: 0
			}
		},
		onLoad() {
			initNFC(function(cardNo) {
				if (_this.cardNoNfc !== cardNo) {
					_this.cardNoNfc = cardNo;
					if (cardNo.length === 12) {
						_this.nfcMethod(cardNo);
					} else {
						uni.showToast({
							title: '卡号读取错误，请重刷',
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: '请勿重复刷卡',
						icon: 'none'
					})
				}
			});
		},
		onUnload() {
			this.cardNoNfc = '';
			closeNFC();
		},
		methods: {
			handChange() {
				if (timer) {
					clearTimeout(timer)
					timer = null
				}
				timer = setTimeout(() => {
					this.setValue()
					clearTimeout(timer)
					timer = null
				}, 300)
			},
			setValue() {
				setNfcText(this.keyWord)
			},
			radioChange: function(evt) {
				for (let i = 0; i < this.items.length; i++) {
					if (this.items[i].value === evt.detail.value) {
						this.current = i;
						setNfcType(this.items[i].value)
						break;
					}
				}
			}
		}
	}
</script>

<style>
	.uni-list {
		display: flex;
	}

	.uni-list-cell {
		display: flex;
		padding: 20rpx 24rpx;
		border-bottom: 1rpx solid #f2f2f2;
	}

	.input {
		margin-top: 40rpx;
		padding: 20rpx;
		border-bottom: 1rpx solid #f2f2f2;
	}
</style>